
package com.oahcfly.chgame.core.ui;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import com.badlogic.gdx.scenes.scene2d.utils.ActorGestureListener;
import com.badlogic.gdx.utils.Align;
import com.badlogic.gdx.utils.Array;
import com.oahcfly.chgame.core.Chao;
import com.oahcfly.chgame.core.mvc.CHActor;

/**
 * 
 * 
 * 滑动切换多个页面，底部显示进度点
 * 
 * @author haocao
 *
 */
public class CHViewPager extends Group {

	private Array<Texture> picTextureArray;
	private CHActor picActor;
	private Texture dotBgTexture, dotLightTexture;
	private Table dotTable;
	private int MAXPOS;

	public CHViewPager (Array<Texture> picArray, Texture dotDefaultTexture, Texture dotLightTexture) {
		picTextureArray = picArray;
		MAXPOS = picArray.size - 1;

		picActor = CHActor.obtain();

		this.dotBgTexture = dotDefaultTexture;
		this.dotLightTexture = dotLightTexture;

		picActor.setBgTexture(picArray.get(0));
		if (picActor.getWidth() > Chao.gameW) {
			picActor.setWidth(Chao.gameW);
		}
		if (picActor.getHeight() > Chao.gameH) {
			picActor.setHeight(Chao.gameH);
		}
		addActor(picActor);
		setSize(picActor.getWidth(), picActor.getHeight());

		dotTable = initDotTable();
		addActor(dotTable);

		CHActor dotActor = (CHActor)dotTable.getCells().get(curPos).getActor();
		dotActor.setBgTexture(dotLightTexture);

		addListener(new ActorGestureListener() {

			@Override
			public void fling (InputEvent event, float velocityX, float velocityY, int button) {
				if (velocityX < -10) {
					changePos(1);
				} else if (velocityX > 10) {
					// 
					changePos(-1);
				}
			}

		});
	}

	private Table initDotTable () {
		int size = picTextureArray.size;

		Table dotTable = new Table();
		for (int i = 0; i < size; i++) {
			CHActor actor = CHActor.obtain();
			actor.setBgTexture(dotBgTexture);
			dotTable.add(actor).pad(10);
		}
		dotTable.pack();

		dotTable.setPosition(getWidth() / 2, dotTable.getHeight(), Align.center);
		return dotTable;
	}

	private int curPos = 0;

	/**
	 * 
	 * 移动图片位置
	 * @param changeValue -1 从左向右滑，1 从右向左滑
	 */
	protected void changePos (int changeValue) {
		curPos += changeValue;
		if (curPos > MAXPOS) {
			curPos = 0;
		} else if (curPos < 0) {
			curPos = MAXPOS;
		}
		if (curPos >= 0 && curPos <= MAXPOS) {
			for (Actor actor : dotTable.getChildren()) {
				CHActor tmp = (CHActor)actor;
				tmp.setBgTexture(dotBgTexture);
			}

			CHActor dotActor = (CHActor)dotTable.getCells().get(curPos).getActor();
			dotActor.setBgTexture(dotLightTexture);

			picActor.setBgTexture(picTextureArray.get(curPos));
		} else {
			curPos -= changeValue;
		}
	}

	public Table getDotTable () {
		return dotTable;
	}

	public int getCurPos () {
		return curPos;
	}
	
}
